package pl.edu.pw.ee.buildcity.notifiers;

import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.notifiers.preparators.BuildNotificationPreparator;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mateusz
 * @since 2010-02-14
 */
public class MailNotifier extends AbstractNotifier {

	private static final Logger log = Logger.getLogger(MailNotifier.class);

	@Resource(name = "mailSender")
	private JavaMailSender mailSender;

	@Override
	protected void notifyEndOfBuild(List<String> recipients, BuildActivity buildActivity) throws CouldNotNotifyException {
		BuildNotificationPreparator preparator = new BuildNotificationPreparator(buildActivity, velocityEngine);
		for (String recipient : recipients) {
			preparator.specifyRecipient(recipient);
			sendEmail(preparator, recipient);
		}
	}

	private void sendEmail(MimeMessagePreparator preparator, String recipient) {
		try {
			this.mailSender.send(preparator);
			log.info("Email successfully sent to: " + recipient);

		} catch (Exception e) {
			CouldNotNotifyException notifyException = new CouldNotNotifyException(recipient, e);
			log.error(notifyException.getMessage());
			throw notifyException;
		}
	}
}